<script setup lang="ts">
  import { Session } from '@/utils/storage.ts';
  import { type DramaEpisode, type DramaItem, getDramaEpisodeListAxios } from '@/api/drama-management.ts';
  import SolarCopyLineDuotone from '~icons/solar/copy-line-duotone';
  import SolarDownloadMinimalisticOutline from '~icons/solar/download-minimalistic-outline';
  import { useClipboardHelper } from '@/utils/useClipboard.ts';
  import { chunkArray } from '@/utils/array.ts';
  import { downloadPicture } from '@/utils/common';

  const route = useRoute();
  const dramaValue = ref<DramaItem | null>(null);
  const dramaId = ref<number | null>(null);
  const dramaEpisodeList = ref<DramaEpisode[]>([]);
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });
  const currentEpisode = ref<DramaEpisode | null>(null);

  const getViewData = async () => {
    dramaEpisodeList.value = [];
    try {
      pageLoad.loadState = true;
      const res = await getDramaEpisodeListAxios(dramaId.value!);
      dramaEpisodeList.value = res.data;
      if (dramaEpisodeList.value.length) {
        currentEpisode.value = dramaEpisodeList.value[0] || null;
      }
      pageLoad.loadState = false;
    } catch (error) {
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
    }
  };

  const changeCurrentEpisode = (episode: DramaEpisode) => {
    currentEpisode.value = episode;
  };

  const dramaEpisodeGetter = computed(() => {
    const list: DramaEpisode[][] = chunkArray(dramaEpisodeList.value, 50);
    const numList: Record<'desc' | 'idx', number | string>[] = [];
    list.forEach((item, idx) => {
      numList.push({
        idx,
        desc: `${idx * 50 + 1}-${item.length + idx * 50}集`,
      });
    });
    return {
      list,
      numList,
    };
  });

  const videoInfoGetter = computed(() => {
    if (currentEpisode.value) {
      return {
        episodeCover: currentEpisode.value.episodeCover,
        url: currentEpisode.value.episodeUrl,
      };
    }
    return {
      episodeCover: '',
      url: '',
    };
  });

  const downloadDramaCover = () => {
    downloadPicture(dramaValue.value!.dramaCover!, dramaValue.value?.dramaTitle);
  };

  const { copyClipboard } = useClipboardHelper();
  /** 复制 */
  function clipboard(text: string | undefined) {
    if (text) {
      copyClipboard(text);
    }
  }

  onBeforeMount(() => {
    dramaId.value = 'dramaId' in route.query && !isNaN(Number(route.query.dramaId)) ? Number(route.query.dramaId) : null;
    if (dramaId.value) {
      const dramaItem = Session.get(`dramaPreview_${dramaId.value}`);
      if (dramaItem) {
        dramaValue.value = dramaItem;
      }
      getViewData();
    }
  });

  onUnmounted(() => {
    Session.remove(`dramaPreview_${dramaId.value}`);
  });
</script>

<template>
  <base-load-page :loadState="pageLoad.loadState" :description="pageLoad.description" :pageLoadButton="[{ text: '重新加载', callBack: () => getViewData() }]">
    <div class="wrap">
      <el-scrollbar>
        <div class="drama-info">
          <base-image
            style="width: 90px; height: 120px; border-radius: 4px"
            :src="dramaValue?.dramaCover"
            previewTeleported
            :previewSrcList="[dramaValue?.dramaCover || '']"
          ></base-image>
          <div class="drama-desc">
            <p class="name">
              <span>{{ dramaValue?.dramaTitle }}</span>
              <el-icon @click="clipboard(dramaValue?.dramaTitle)"><solar-copy-line-duotone></solar-copy-line-duotone></el-icon>
            </p>
            <p class="drama-id" @click="clipboard(dramaValue?.dramaId + '')">
              <span>ID:{{ dramaValue?.dramaId }}</span>
              <el-icon><solar-copy-line-duotone></solar-copy-line-duotone></el-icon>
            </p>
            <div class="status">
              <div>
                <el-tag v-if="dramaValue?.dyStatus === 1" key="el-tag-1" type="success" size="small">抖音上架</el-tag>
                <el-tag v-else key="el-tag-2" type="info" size="small">抖音下架</el-tag>
              </div>
              <div>
                <el-tag v-if="dramaValue?.wechatStatus === 1" key="el-tag-1" type="success" size="small">微信上架</el-tag>
                <el-tag v-else key="el-tag-2" type="info" size="small">微信下架</el-tag>
              </div>
              <div>
                <el-tag v-if="dramaValue?.ksStatus === 1" key="el-tag-1" type="success" size="small">快手上架</el-tag>
                <el-tag v-else key="el-tag-2" type="info" size="small">快手下架</el-tag>
              </div>
            </div>
            <p>{{ dramaValue?.seqNum }}集</p>
          </div>
        </div>
        <div v-if="dramaValue?.dramaCover" class="download-drama-img" @click="downloadDramaCover">
          <span>封面下载</span>
          <el-icon><solar-download-minimalistic-outline></solar-download-minimalistic-outline></el-icon>
        </div>
        <div class="brief-introduction">
          <span>{{ dramaValue?.dramaDesp }}</span>
          <el-icon @click="clipboard(dramaValue?.dramaDesp)"><solar-copy-line-duotone></solar-copy-line-duotone></el-icon>
        </div>
        <div class="reasons-for-recommendation">
          <span>{{ dramaValue?.dramaRecommendation }}</span>
        </div>
        <div class="episode-wrap">
          <div class="title">剧集列表（{{ dramaEpisodeList.length }}）</div>
          <div class="preview-video-wrap">
            <div class="preview-video">
              <div class="video">
                <video controls controlslist="nodownload" autoplay :src="videoInfoGetter.url" :poster="videoInfoGetter.episodeCover"></video>
              </div>
            </div>
            <div class="video-control-wrap">
              <div class="video-control">
                <el-tabs type="border-card">
                  <el-tab-pane v-for="i in dramaEpisodeGetter.numList" :key="i.idx" :label="i.desc as string">
                    <el-scrollbar>
                      <li
                        v-for="j in dramaEpisodeGetter.list[i.idx as number]"
                        :key="j.episodeId"
                        class="episode-item"
                        :class="{ 'episode-item-ac': currentEpisode && currentEpisode.episodeId === j.episodeId }"
                        @click="changeCurrentEpisode(j)"
                      >
                        {{ j.episodeTitle }}
                      </li>
                    </el-scrollbar>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </base-load-page>
</template>

<style scoped lang="scss">
  .wrap {
    width: 100%;
    height: 100%;
    padding: 10px;

    .drama-info {
      display: flex;
      gap: 20px;

      .drama-desc {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        p:nth-child(1) {
          display: flex;
          gap: 4px;
          font-size: 16px;

          .el-icon {
            cursor: pointer;
          }
        }

        p:nth-child(2) {
          display: flex;
          gap: 4px;
          color: rgba(0, 0, 0, 0.64);
          cursor: pointer;

          &:hover {
            color: #ff0000;
          }
        }

        p:nth-child(4) {
          font-size: 24px;
        }

        .status {
          display: flex;
          gap: 10px;
        }
      }
    }

    .download-drama-img {
      width: 90px;
      padding-top: 10px;
      text-align: center;
      cursor: pointer;

      &:hover {
        color: #ff0000;
      }
    }

    .brief-introduction,
    .reasons-for-recommendation {
      padding-right: 30px;
      margin-top: 40px;
      margin-bottom: 40px;
      font-size: 14px;
      font-weight: normal;
      color: rgba(0, 0, 0, 0.64);

      .el-icon {
        margin-left: 4px;
        cursor: pointer;
      }

      &:before {
        display: block;
        margin-bottom: 12px;
        font-size: 16px;
        font-weight: 500;
        line-height: 24px;
        color: #000000;
      }
    }

    .brief-introduction:before {
      content: '作品简介';
    }

    .reasons-for-recommendation:before {
      content: '推荐理由';
    }

    .episode-wrap {
      .title {
        display: block;
        margin-bottom: 12px;
        font-size: 16px;
        font-weight: 500;
        line-height: 24px;
      }

      .preview-video-wrap {
        display: flex;
        gap: 20px;
        width: 100%;

        .preview-video {
          flex-grow: 1;
          overflow: hidden;
          border-radius: 6px;

          .video {
            position: relative;
            width: 100%;
            max-width: 100%;
            height: 0;
            padding-top: 56.25%;

            video {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              outline: none;
            }
          }
        }

        .video-control-wrap {
          position: relative;
          flex-shrink: 0;
          width: 680px;
          height: 0;
          padding-top: calc(56.25% - 393.75px);

          .video-control {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;

            .el-tabs {
              height: 100%;

              .el-tab-pane {
                height: 100%;
              }
            }

            .episode-item {
              display: flex;
              align-items: center;
              justify-content: space-between;
              height: 46px;
              padding-right: 16px;
              padding-left: 12px;
              margin-right: 8px;
              margin-bottom: 8px;
              cursor: pointer;
              border: none;
              border-radius: 4px;

              &:hover {
                background-color: rgba(187, 187, 189, 0.22);
              }
            }

            .episode-item-ac {
              background-color: rgba(255, 95, 0, 0.04);
              border: 1px solid rgb(255, 95, 0);
            }
          }
        }
      }
    }
  }

  .dark {
    .drama-desc {
      .drama-id span,
      .drama-id .el-icon {
        color: rgb(207, 201, 201);
      }
    }

    .brief-introduction,
    .reasons-for-recommendation {
      color: rgba(216, 212, 212, 1);

      &:before {
        color: #ffffff;
      }
    }
  }
</style>
